/**
 * Created by Administrator on 2015/1/11.
 */
var Model = require('../node_modules/mongoose/lib/model');

Model.findPagination = function(condition, populate, pages, columns, sort ,callback) {

    var self = this;
    var condition = condition ||{}; //查下条件
    var columns = columns; //查询列
    var sort = sort || {}; //排序

    var currentPage = (pages && pages.num) || 1; //当前页
    var limit = (pages && pages.limit) || 10; //每页显示数量

    var skipFrom = (currentPage * limit) - limit;

    var query;

    if(columns){
        query = self.find(condition, columns);
    } else {
        query = self.find(condition);
    }

    query = query.sort(sort).skip(skipFrom).limit(limit);

    if(populate){
        query = query.populate(populate);
    }

    query.exec(function(error, results) {
        if (error) {
            callback(error, null, null);
        } else {
            self.count(condition, function(error, count) {
                if (error) {
                    callback(error, null, null);
                } else {
                    var pageCount = Math.ceil(count / limit);
                    callback(null, currentPage, count, limit, pageCount, results);
                }
            });
        }
    });
}